package com.example.goods.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.commons.exception.BusinessException;
import com.example.commons.inspect.ParamsInspect;
import com.example.commons.time.TimeTools;
import com.example.goods.mapper.ArticleMapper;
import com.example.goods.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    ArticleMapper articleMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addArticle(String name, String summary, String price, int number) {
        ParamsInspect.IsNull(name, "商品名称");
        ParamsInspect.IsNull(summary, "商品简介");
        ParamsInspect.IsNumber(price, "商品价格");
        ParamsInspect.IsNumber(String.valueOf(number), "商品数量");

        String id = String.valueOf(System.currentTimeMillis());
        String createTime = TimeTools.getTime();
        if (1 != articleMapper.addArticle(id, name, summary, price, number, createTime)) {
            throw new BusinessException("添加失败");
        }
    }

    @Override
    public Object[] selectArticleByShow(int page, int size) {
        IPage<Map<String, Object>> iPage = new Page<>(page, size);
        articleMapper.selectArticleByShow(iPage);
        return new Object[]{iPage.getPages(), iPage.getTotal(), iPage.getRecords()};
    }

    @Override
    public Map<String, Object> selectArticle(String id) {
        Map<String, Object> map = articleMapper.selectArticle(id);
        if (null == map) {
            throw new BusinessException("商品不存在");
        }
        return map;
    }

    @Override
    public Map<String, Object> selectArticleForUpdate(String id) {
        Map<String, Object> map = articleMapper.selectArticleForUpdate(id);
        if (null == map) {
            throw new BusinessException("商品不存在");
        }
        return map;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateOrderNumber(String orderId) {
        if (1 != articleMapper.updateOrderNumber(orderId)) {
            throw new BusinessException("操作失败");
        }
    }
}
